<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form
      ref="dictEntryFormRef"
      :model="form"
      label-width="120px"
      :rules="rules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('dictEntry.dictCode')" prop="dictCode">
            <el-input
              v-model="form.dictCode"
              :placeholder="$t('dictEntry.dictCodeRequired')"
              maxlength="30"
              show-word-limit
              clearable
              :readonly="update"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('dictEntry.dictName')" prop="dictName">
            <el-input
              v-model="form.dictName"
              :placeholder="$t('dictEntry.dictNameRequired')"
              maxlength="60"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('dictEntry.typeCode')" prop="typeCode">
            <jmash-select
              v-model="form.typeCode"
              :placeholder="$t('dictEntry.typeCode')"
              :data="Dict.normalDictType.values"
              class="w-full"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('dictEntry.enable')" prop="enable">
            <el-switch v-model="form.enable" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('dictEntry.description')" prop="description">
            <el-input
              v-model="form.description"
              :placeholder="$t('dictEntry.descriptionRequired')"
              maxlength="120"
              show-word-limit
              clearable
              :rows="3"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import type { PropType } from "vue";

import { ref, reactive, toRef } from "vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
const { t } = useI18n();

import type {
  DictEntryKey,
  DictEntryFormReq,
  DictEntryCreateReq,
  DictEntryUpdateReq,
} from "@/api/dict/os-dict-entry/types";
import { dictEntryApi } from "@/api/dict/os-dict-entry/index";
import { Dict } from "@/api/dict/dict";
//加载业务数据.
Dict.normalDictType.useValues();

const dictEntryFormRef = ref<FormInstance>();

let form: DictEntryFormReq = reactive<DictEntryFormReq>({
  requestId: Math.random() * 10 + "",
  updateMask: "dictName,enable,description",
  enable: true,
});

const rules = reactive<FormRules<DictEntryFormReq>>({
  typeCode: [
    {
      required: true,
      message: t("dictEntry.typeCode"),
      trigger: "change",
    },
  ],
  dictCode: [
    {
      required: true,
      message: t("dictEntry.dictCodeRequired"),
      trigger: "blur",
    },
  ],
  dictName: [
    {
      required: true,
      message: t("dictEntry.dictNameRequired"),
      trigger: "blur",
    },
  ],
});

const model = defineModel<boolean>();

const props = defineProps({
  entityKey: {
    type: Object as PropType<DictEntryKey>,
    default: () => {},
  },
});

//设置字典类型
form.typeCode = props.entityKey.typeCode;

const emits = defineEmits(["refresh"]);

const keys = Object.keys(props.entityKey);

const update = ref(keys.length >= 2);

if (update.value) {
  dictEntryApi.findById(props.entityKey).then(({ data }) => {
    Object.assign(form, data);
  });
}
// 提交表单校验
const submitForm = async () => {
  await dictEntryFormRef.value?.validate((valid) => {
    if (valid) {
      if (update.value) {
        dictEntryApi.update(form as DictEntryUpdateReq).then((response) => {
          console.log(response);
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      } else {
        dictEntryApi.create(form as DictEntryCreateReq).then((response) => {
          console.log(response);
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      }
    }
  });
};

// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}
</script>
<style scoped lang="scss">
.w-full {
  width: 100% !important;
}
</style>
